package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dto.RegistrationDTO;
import com.example.mapper.EventMapper;
import com.example.mapper.RegistrationMapper;
import com.example.mapper.UserMapper;
import com.example.pojo.Event;
import com.example.pojo.Registration;
import com.example.pojo.User;
import com.example.service.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class RegistrationServiceImpl implements RegistrationService {
    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EventMapper eventMapper;

    @Override
    public void saveRegistration(RegistrationDTO registrationDTO) {

        // 检查用户是否存在，如果不存在则创建用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", registrationDTO.getPhone());
        User user = userMapper.selectOne(userQueryWrapper);

        // 如果用户不存在，创建新用户
        if (user == null) {
            user = new User();
            user.setUsername(registrationDTO.getUserName());
            user.setPassword("123456");
            user.setPhone(registrationDTO.getPhone());
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        // 检查用户是否已经报名了该活动
        QueryWrapper<Registration> registrationQueryWrapper = new QueryWrapper<>();
        registrationQueryWrapper.eq("user_id", user.getId())
                                .eq("event_id", registrationDTO.getEventId());
        Registration existingRegistration = registrationMapper.selectOne(registrationQueryWrapper);

        if (existingRegistration != null) {
            throw new IllegalArgumentException("您已经报名了该活动，无法重复报名");
        }

        // 检查活动是否已满
        Event event = eventMapper.selectById(registrationDTO.getEventId());
        if (event == null) {
            throw new IllegalArgumentException("活动不存在");
        }

        if (event.getNumber() >= event.getMaxNumber()) {
            throw new IllegalArgumentException("活动已满，无法报名");
        }

        // 更新活动的已报名人数
        event.setNumber(event.getNumber() + 1);
        eventMapper.updateById(event);

        // 插入新的报名信息
        Registration registration = new Registration();
        registration.setUserId(user.getId());
        registration.setEventId(registrationDTO.getEventId());
        registration.setStatus(1);
        registration.setCreateTime(LocalDateTime.now());
        registrationMapper.insert(registration);

    }
}



